package com.cxm.qyyz.base.activity;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cxm.qyyz.R;
import com.cxm.qyyz.app.Navigator;
import com.cxm.qyyz.base.mvp.BaseContract;
import com.cxm.qyyz.core.http.DefaultObserver;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;


import java.util.ArrayList;

import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.dialog.DialogLayer;

public abstract class BaseListActivity<M, T extends BaseContract.BasePresenter> extends BaseActivity<T>
        implements OnRefreshLoadMoreListener {

    protected Activity mActivity;
    //列表
    public RecyclerView list;
    public SmartRefreshLayout refreshLayout;
    LinearLayout empty;
    public  ImageView emptyImage;
    public TextView emptyText;
    public TextView emptyEnter;

    public BaseQuickAdapter listAdapter;


    //空文案点击事件
    public void onEmptyClick(){
    }
    //空文案
    protected abstract int getEmptyText();
    //下一步文案  空等于不显示
    protected  String getNextText() {
        return "";
    }

    //空图片
    protected abstract int getEmptyImage();


    public String getTitles() {
        return getTitle().toString();
    }

    protected RecyclerView.LayoutManager getLayoutLayoutManager() {
        return new LinearLayoutManager(this);
    }

    protected abstract BaseQuickAdapter getListAdapter();

    public DefaultObserver<ArrayList<M>> getCallBack() {
        return new DefaultObserver<ArrayList<M>>(this) {

            @Override
            protected void onSuccess(ArrayList<M> data) {
                runOnUiThread(() -> {
                    if (null != data){
                        if (data.size()>0){
                            if (pagerNumber == 1) {
                                listAdapter.setNewData(data);
                                refreshLayout.setEnableLoadMore(true);
                            } else {
                                listAdapter.addData(data);
                            }
                            pagerNumber++;
                            empty.setVisibility(View.GONE);
                            list.setVisibility(View.VISIBLE);
                            setEnableLoadMore(true);
                        }else {
                            if (pagerNumber == 1){
                                listAdapter.setNewData(new ArrayList());
                            }
                            if (listAdapter.getData().size()==0){
                                empty.setVisibility(View.VISIBLE);
                                list.setVisibility(View.GONE);
                            }
                            setEnableLoadMore(false);

                        }
                    }else {
                        if (pagerNumber == 1){
                            listAdapter.setNewData(new ArrayList());
                        }
                        if (listAdapter.getData().size()==0){
                            empty.setVisibility(View.VISIBLE);
                            list.setVisibility(View.GONE);
                        }
                        setEnableLoadMore(false);
                    }
                    closeLoding();
                });

            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                if (listAdapter.getData().size() == 0) {
                    empty.setVisibility(View.VISIBLE);
                    list.setVisibility(View.GONE);
                } else {
                    empty.setVisibility(View.GONE);
                    list.setVisibility(View.VISIBLE);
                }
                closeLoding();
            }

        };
    }


    public void setEnableLoadMore(boolean isrefresh) {
        refreshLayout.setEnableLoadMore(isrefresh);
    }


    public void closeLoding() {
        if (null!=refreshLayout){
            refreshLayout.finishLoadMore();
            refreshLayout.finishRefresh();
        }
    }

    public int pagerNumber = 1;


    protected abstract void initUrl();

    @Override
    public void onLoadMore(@NonNull com.scwang.smart.refresh.layout.api.RefreshLayout refreshLayout) {
        initUrl();
    }

    @Override
    public void onRefresh(@NonNull com.scwang.smart.refresh.layout.api.RefreshLayout refreshLayout) {
        pagerNumber = 1;
        initUrl();
    }


    @LayoutRes
    protected abstract int getLayoutId();


    @Override
    protected void initEvents() {
        mActivity = this;
        list = findViewById(R.id.list);
        refreshLayout = findViewById(R.id.refreshLayout);
        empty = findViewById(R.id.empty);
        emptyImage = findViewById(R.id.empty_image);
        emptyText = findViewById(R.id.empty_text);
        emptyEnter = findViewById(R.id.empty_enter);

        refreshLayout.setOnRefreshLoadMoreListener(this);
        list.setLayoutManager(getLayoutLayoutManager());
        listAdapter = getListAdapter();
        list.setAdapter(listAdapter);

        emptyImage.setImageDrawable(getResources().getDrawable(getEmptyImage()));
        emptyText.setText(getResources().getString(getEmptyText()));
        emptyEnter.setText(getNextText());
        emptyEnter.setVisibility(TextUtils.isEmpty(getNextText())?View.GONE : View.VISIBLE);
        emptyEnter.setOnClickListener(v -> onEmptyClick());
    }


    @Override
    public void onReload() {
        initUrl();
    }

    protected void initBeforeBindLayout() {

    }

    protected boolean supportEventBus() {
        return false;
    }

    protected void registerEventBus() {
    }

    protected void unregisterEventBus() {
    }

    protected void setScreenOrientation() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_BEHIND);
    }

//    protected void initStatusBar() {
//        StatusBarPlus.setColor(this, getResources().getColor(R.color.color_ffffff));
//        StatusBarPlus.setStatusBarMode(this, true);
//    }

    protected boolean supportStateController() {
        return true;
    }

    protected boolean supportSwipeBack() {
        return true;
    }
    @Override
    public void jumpToLogin() {

    }

    @Override
    public void onDismiss() {
        super.onDismiss();
        closeLoding();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, ev)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(v);   //收起键盘
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {  //判断得到的焦点控件是否EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);//得到输入框在屏幕中上下左右的位置
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击位置如果是EditText的区域，忽略它，不收起键盘。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略
        return false;
    }

    protected void hideKeyboard(View view) {
        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null) {
            im.hideSoftInputFromWindow(view.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    DialogLayer dialogLayer;

    /**
     * dialog
     * date 2021/12/20
     * author yzx
     */
    public void showDialog() {
//        if (null == dialogLayer)
//            dialogLayer = AnyLayer.dialog(this)
//                    .contentView(R.layout.item_progressbar)
//                    .gravity(Gravity.CENTER)
//                    .cancelableOnTouchOutside(false)
//                    .cancelableOnClickKeyBack(false);
//
//        dialogLayer.show();
    }

    /**
     * 取消弹框
     * date 2021/12/20
     * author yzx
     */
    public void dismiss() {
        if (null != dialogLayer) dialogLayer.dismiss();
    }

    //全局定义
    private long lastClickTime = 0L;
    // 两次点击间隔不能少于1000ms
    private static final int FAST_CLICK_DELAY_TIME = 1000;


    public void onClick(View view) {
        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
            return;
        }
        lastClickTime = System.currentTimeMillis();
        onClicks(view);
    }

    public void onClicks(View view) {
    }
}
